package cn.zzdt4j.auth.security;

import cn.zzdt4j.auth.model.biz.user.LoginUser;
import lombok.AllArgsConstructor;
import lombok.SneakyThrows;
import org.springframework.expression.AccessException;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * The type Auth manager.
 *
 * @author by <a href="mailto:ligang941012@gmail.com">gang.Li</a>
 * @since 2023 /11/6 19:38
 */
@Component
@AllArgsConstructor
public class AuthManager {

    private final JwtTokenManager jwtTokenManager;

    private final AuthenticationManager authenticationManager;

    private final UserDetailsService userDetailsService;

    @SneakyThrows
    public String resolveTokenFromUser(String userName, String rawPassword) {
        try {
            final HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
            LoginUser loginUser = new LoginUser();
            loginUser.setPassword(rawPassword);
            request.setAttribute("loginUser", loginUser);
            final UserDetails userDetails = userDetailsService.loadUserByUsername(userName);

        } catch (AuthenticationException e) {
            throw new AccessException("Unknown user.");
        }
        return jwtTokenManager.createToken(userName);
    }
}
